package com.ejlchina.tool.base

import android.bluetooth.BluetoothGattCharacteristic
import android.os.Bundle
import android.os.CountDownTimer
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.viewbinding.ViewBinding
import com.ejlchina.tool.bean.BleDeviceBean
import com.ejlchina.tool.constant.LOADING_TIME_OUT
import com.ejlchina.tool.util.getDownwardCommand
import com.ejlchina.tool.util.showToast
import com.ejlchina.tool.viewmodel.MainViewModel
import com.ejlchina.tool.viewmodel.PRIORITY_WRITE_DEFAULT
import com.huyuhui.fastble.data.BleDevice
import com.shencoder.loadingdialog.LoadingDialog

abstract class BaseBindingActivity<VB : ViewBinding> : AppCompatActivity() {
    private lateinit var mMiniLoadingDialog: LoadingDialog
    lateinit var binding: VB
    protected val viewModel: MainViewModel by viewModels()
    private var timer: CountDownTimer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initMiniLoadingDialog()
        binding = getViewBinding()
        setContentView(binding.root)
    }

    //倒计时的方式一
    private fun countDownTimer() {
        timer?.cancel()
        val num = LOADING_TIME_OUT
        timer = object : CountDownTimer((num + 1) * 1000L, 1000L) {
            override fun onTick(millisUntilFinished: Long) {}
            override fun onFinish() {
                dismissLoading()
                showToast("数据获取失败")
            }
        }
        timer?.start()
    }

    private fun initMiniLoadingDialog() {
        if (!this::mMiniLoadingDialog.isInitialized){
            mMiniLoadingDialog = LoadingDialog.builder(this).setCancelable(true).showHintText(false).create()
        }
    }

    fun dismissLoading() {
        timer?.cancel()
        if (mMiniLoadingDialog.isShowing){
            mMiniLoadingDialog.dismiss()
        }
    }

    fun showLoading(showText: String = "请稍候"){
        if (!mMiniLoadingDialog.isShowing){
            countDownTimer()
            mMiniLoadingDialog.setHintText(showText)
            mMiniLoadingDialog.show()
        }
    }

    fun setCommandData(bleDevice: BleDeviceBean, command: String, commandVariable: String,isForFireUpload: Boolean = false,isShowLoading: Boolean = true) {
        if (isShowLoading){
            showLoading()
        }

        viewModel.writeByQueue(bleDevice, getDownwardCommand(bleDevice, command, commandVariable),false,
            isForFileUpload = isForFireUpload,
            priority = PRIORITY_WRITE_DEFAULT,
            writeType = BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE
        )
    }

    override fun onDestroy() {
        super.onDestroy()
        timer?.cancel()
    }

    abstract fun getViewBinding(): VB

}